from django.contrib import auth
from django.contrib.auth.models import User
from django.template import RequestContext
from django.db import IntegrityError
from django.shortcuts import render_to_response, get_object_or_404, redirect
from RSM.my_friends.models import RSMUser
from RSM.util import printDebug, getExtend, verifySessionValidity, isSafeName

def index(request):
    if request.user.is_authenticated():
        if request.GET.get("change"):
            if request.POST:
                if (request.POST.get("pass") == request.POST.get("repPass")):
                    request.user.set_password(request.POST.get("pass"))
                    request.user.save()
                    auth.logout(request)
                    return render_to_response("basic/welcomepage.html",context_instance=RequestContext(request))
                else:
                    return render_to_response("basic/errorPage.html", {'extend': getExtend(request), 'message':reasons['passMismatch']}, context_instance=RequestContext(request)) 
            else:
                return redirect('/')
        if request.GET.get("logout"):
            auth.logout(request)
            variables = {}
            if request.GET.get("reason"):
                reason = request.GET.get("reason")
                if reasons.has_key(reason):
                    variables = {"reason": reasons[reason]}
            return render_to_response('basic/welcomepage.html', variables, context_instance=RequestContext(request))
        rsmUser = get_object_or_404(RSMUser, user__username=request.user.username) 
        return render_to_response('basic/homepage.html', {"user": rsmUser}, context_instance=RequestContext(request))
    else:
        return render_to_response('basic/welcomepage.html', context_instance=RequestContext(request))

def custom_login(request):
    if request.POST:
        action = request.POST.get('action')
        printDebug(action)
        if (action == 'Login'):
            username = request.POST.get('username', '')
            password = request.POST.get('password', '')
            user = auth.authenticate(username=username, password=password)
            if (user is not None and user.is_active):
                auth.login(request, user)
                rsmUser = get_object_or_404(RSMUser, user__username=request.user.username) 
                return render_to_response('basic/homepage.html', {"user": rsmUser}, context_instance=RequestContext(request))
            else:
                return render_to_response('basic/errorPage.html', {'extend': getExtend(request), 'message': reasons['uNamePassErr']},context_instance=RequestContext(request))
        else:
            return redirect('/')
    else:
        return redirect('/')

def about_us(request):
    return render_to_response('basic/aboutUs.html', {'extend': getExtend(request)}, context_instance=RequestContext(request))

def custom_register(request):
    if request.POST:
        email = request.POST.get('email','')
        password = request.POST.get('pass', '')
        repeatPassword = request.POST.get('repPass', '')
        username = request.POST.get('inputUsername','')
        if not __isLegalUsername(username):
            return render_to_response('basic/errorPage.html', {'extend': getExtend(request), 'message': reasons['illUName']}, context_instance=RequestContext(request))
        if password != repeatPassword:
            return render_to_response('basic/errorPage.html', {'extend': getExtend(request), 'message': reasons['passMismatch']}, context_instance=RequestContext(request))
        
        try:
            user = User.objects.create_user(username, email, password)
            rsmUser = RSMUser()
            rsmUser.user=user
            rsmUser.save()
        except IntegrityError:
            return render_to_response("basic/errorPage.html", {'extend': getExtend(request), 'message': reasons['userExists']}, context_instance=RequestContext(request))
        user = auth.authenticate(username=username, password=password)
        if user is not None and user.is_active:
            auth.login(request, user)
            return render_to_response('basic/homepage.html', {"username": user}, context_instance=RequestContext(request))
        else:
            return render_to_response('basic/errorPage.html', {'extend': getExtend(request), 'message': reasons['expired']}, context_instance=RequestContext(request))
    return render_to_response('basic/register.html', context_instance=RequestContext(request))

def custom_profile(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag

    rsmUser = get_object_or_404(RSMUser, user__username=request.user.username) 
    return render_to_response("basic/profile.html", {"user": rsmUser},context_instance=RequestContext(request))


def __isLegalUsername(username):
    return username and isSafeName(username) and ' ' not in username and '%' not in username 

reasons = {'expired': 'Your session has expired.', 'passMismatch': "Passwords don't match.", 'uNamePassErr': "Wrong username or password!", 'illUName': "Illegal username.", 'userExists': "Username is already taken."}

